<template>
  <div class="material-management">
    <!-- 操作栏：新增按钮 + 搜索 -->
    <div class="operation-bar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">+ 新增物料</el-button>
      <div class="search-group" style="margin-left: auto;">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入物料名称/品牌"
          style="width: 240px;"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"></el-button>
        <el-button type="primary" icon="el-icon-filter" @click="handleFilter"></el-button>
      </div>
    </div>

    <!-- 物料表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-bottom: 20px;" v-loading="loading">
      <el-table-column label="序号" type="index" width="150" :index="getIndex" />
      <el-table-column prop="materialName" label="材料名称" width="200" />
      <el-table-column prop="materialBrand" label="品牌" width="170" />
      <el-table-column prop="materialSpecifications" label="规格型号" width="150" />
      <el-table-column prop="materialUnit" label="单位" width="80" />
      <el-table-column prop="materialDesc" label="备注" width="200" />
      <el-table-column label="操作" width="156">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pagination.pageSize"
        layout="prev, pager, next, jumper, sizes, total"
        :total="pagination.total"
      />
    </div>

    <!-- 新增/编辑物料对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="500px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="materialForm" label-width="100px">
        <el-form-item label="材料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入材料名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="materialBrand">
          <el-input v-model="form.materialBrand" placeholder="请输入品牌"></el-input>
        </el-form-item>
        <el-form-item label="规格型号" prop="materialSpecifications">
          <el-input v-model="form.materialSpecifications" placeholder="请输入规格型号"></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="materialUnit">
          <el-input v-model="form.materialUnit" placeholder="请输入单位"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="materialPrice">
          <el-input-number v-model="form.materialPrice" :precision="2" :min="0" placeholder="请输入价格"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="materialDesc">
          <el-input type="textarea" v-model="form.materialDesc" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { materialApi } from '@/api/material'

export default {
  name: 'MaterialManagement',
  data() {
    return {
      loading: false,
      submitLoading: false,
      searchKeyword: '',
      tableData: [],
      dialogVisible: false,
      dialogTitle: '新增物料',
      isEdit: false,
      form: {
        materialId: '',
        materialName: '',
        materialBrand: '',
        materialSpecifications: '',
        materialUnit: '',
        materialPrice: 0,
        materialDesc: ''
      },
      rules: {
        materialName: [
          { required: true, message: '请输入材料名称', trigger: 'blur' }
        ],
        materialBrand: [
          { required: true, message: '请输入品牌', trigger: 'blur' }
        ],
        materialSpecifications: [
          { required: true, message: '请输入规格型号', trigger: 'blur' }
        ],
        materialUnit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ]
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 获取序号
    getIndex(index) {
      return (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1
    },
    
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize
        }
        
        const response = await materialApi.getMaterialPage(params)
        if (response.code === 200) {
          this.tableData = response.data.records || []
          this.pagination.total = response.data.total || 0
        } else {
          this.$message.error(response.message || '加载数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    async handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.loadData()
        return
      }
      
      this.loading = true
      try {
        // 使用模糊搜索，同时搜索材料名称和品牌
        const response = await materialApi.fuzzySearchMaterials(this.searchKeyword, this.searchKeyword)
        if (response.code === 200) {
          this.tableData = response.data || []
          this.pagination.total = response.data.length || 0
          this.pagination.currentPage = 1
          
          if (this.tableData.length === 0) {
            this.$message.info('未找到匹配的物料')
          }
        } else {
          this.$message.error(response.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索失败:', error)
        this.$message.error('搜索失败')
      } finally {
        this.loading = false
      }
    },

    // 筛选
    handleFilter() {
      // 可以在这里添加高级筛选功能
      this.$message.info('筛选功能待开发')
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增物料'
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑
    async handleEdit(row) {
      this.dialogTitle = '编辑物料'
      this.isEdit = true
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该物料吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await materialApi.deleteMaterial(row.materialId)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.materialForm.validate()
        
        this.submitLoading = true
        
        let response
        if (this.isEdit) {
          response = await materialApi.updateMaterial(this.form)
        } else {
          response = await materialApi.addMaterial(this.form)
        }
        
        if (response.code === 200) {
          this.$message.success(this.isEdit ? '修改成功' : '新增成功')
          this.dialogVisible = false
          this.loadData()
        } else {
          this.$message.error(response.message || '操作失败')
        }
      } catch (error) {
        if (error !== false) { // 表单验证失败时error为false
          console.error('提交失败:', error)
          this.$message.error('操作失败')
        }
      } finally {
        this.submitLoading = false
      }
    },

    // 重置表单
    resetForm() {
      this.form = {
        materialId: '',
        materialName: '',
        materialBrand: '',
        materialSpecifications: '',
        materialUnit: '',
        materialPrice: 0,
        materialDesc: ''
      }
      if (this.$refs.materialForm) {
        this.$refs.materialForm.resetFields()
      }
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadData()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadData()
    // },

    // // 初始化测试数据
    // async handleInitTestData() {
    //   try {
    //     await this.$confirm('确定要初始化测试数据吗？这将添加5条示例物料数据。', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     })
        
    //     const response = await materialApi.initTestData()
    //     if (response.code === 200) {
    //       this.$message.success(response.message)
    //       this.loadData()
    //     } else {
    //       this.$message.error(response.message || '初始化失败')
    //     }
    //   } catch (error) {
    //     if (error !== 'cancel') {
    //       console.error('初始化测试数据失败:', error)
    //       this.$message.error('初始化测试数据失败')
    //     }
    //   }
    }
  }
}
</script>

<style scoped>
.material-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-group .el-input {
  margin-right: 8px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>